<template>
	<view>
		<!-- 收货地址 -->
		<view class="addr" @tap="selectAddress">
			<view class="icon">
				<image src="../../static/img/addricon.png" mode=""></image>
			</view>
			<view class="right">
				<view class="tel-name">
					<view class="name">
						{{recinfo.name}}
					</view>
					<view class="tel">
						{{recinfo.tel}}
					</view>
				</view>
				<view class="addres">
					{{recinfo.address.region.label}}
					{{recinfo.address.detailed}}
				</view>
			</view>
		</view>
		<!-- 购买商品列表 -->
		<view class="buy-list">
			<view class="row" v-for="(row,index) in buylist" :key="index">
				<view class="goods-info">
					<view class="img">
						<image :src="row.img"></image>
					</view>
					<view class="info">
						<view class="title">{{row.name}}</view>
						<view class="spec">选择{{row.spec}} 数量:{{row.number}}</view>
						<view class="price-number">
							<view class="price">￥{{row.price*row.number}}</view>
							<view class="number">
								
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 提示-备注 -->
		<view class="order">
			<view class="row">
				<view class="left">
					积分 :
				</view>
				<view class="right">
					已扣除{{int}}积分抵扣{{deduction|toFixed}}元
				</view>
			</view>
			<!-- 新增优惠券选择行 -->
			<view class="row" @tap="selectCoupon">
				<view class="left">
					优惠券 :
				</view>
				<view class="right coupon-select">
					<text v-if="selectedCoupon">{{selectedCoupon.name}}</text>
					<text v-else class="placeholder">选择可用优惠券</text>
					<text class="arrow"></text>
				</view>
			</view>
			<view class="row">
				<view class="left">
					备注 :
				</view>
				<view class="right">
					<input placeholder="选填,备注内容" v-model="note" />
				</view>
			</view>
		</view>
		<!-- 明细 -->
		<view class="detail">
			<view class="row">
				<view class="nominal">
					商品金额
				</view>
				<view class="content">
					￥{{goodsPrice|toFixed}}
				</view>
			</view>
			<view class="row">
				<view class="nominal">
					运费
				</view>
				<view class="content">
					￥+{{freight|toFixed}}
				</view>
			</view>
			<view class="row">
				<view class="nominal">
					积分抵扣
				</view>
				<view class="content">
					￥-{{deduction|toFixed}}
				</view>
			</view>
			<!-- 新增优惠券抵扣行 -->
			<view class="row" v-if="selectedCoupon">
				<view class="nominal">
					优惠券抵扣
				</view>
				<view class="content">
					￥-{{selectedCoupon.discount|toFixed}}
				</view>
			</view>
		</view>
		<view class="blck">
			
		</view>
		<view class="footer">
			<view class="settlement">
				<view class="sum">合计:<view class="money">￥{{sumPrice|toFixed}}</view></view>
				<view class="btn" @tap="toPay">提交订单</view>
			</view>
		</view>
	</view>
</template>

<script>
	import api from '@/utils/api.js';
	
	export default {
		data() {
			return {
				buylist:[],		//订单列表
				goodsPrice:0.0,	//商品合计价格
				sumPrice:0.0,	//用户付价格
				freight:12.00,	//运费
				note:'',		//备注
				int:1200,		//抵扣积分
				deduction:0,	//抵扣价格
				seckillToken: '', // 秒杀token
				isSeckillOrder: false, // 是否为秒杀订单
				isFirstLoad: true, // 新增：标记是否首次加载
				recinfo:{id:1,name:"大黑哥",head:"大",tel:"18816881688",address:{region:{"label":"广东省-深圳市-福田区","value":[18,2,1],"cityCode":"440304"},detailed:'深南大道1111号无名摩登大厦6楼A2'},isDefault:true},
				// 优惠券相关数据
				selectedCoupon: null, // 选中的优惠券
				availableCoupons: [] // 可用优惠券列表，改为空数组，从API获取
			};
		},
		onLoad(options) {
			// 首次进入页面时获取默认地址
			if (this.isFirstLoad) {
				this.loadDefaultAddress();
				this.isFirstLoad = false;
			}
			
			// 处理从秒杀页面传递过来的参数
			if (options.type === 'seckill') {
				const goodsId = options.goodsId;
				const goodsName = decodeURIComponent(options.goodsName || '');
				const price = parseFloat(options.price || 0);
				const img = decodeURIComponent(options.img || '');
				const token = options.token || '';
				
				// 保存秒杀token，用于提交订单时扣减库存
				this.seckillToken = token;
				this.isSeckillOrder = true;
				
				// 创建秒杀商品订单
				this.buylist = [{
					id: goodsId,
					name: goodsName,
					price: price,
					img: img,
					number: 1,
					spec: '秒杀商品'
				}];
				
				// 计算价格
				this.goodsPrice = price;
				this.deduction = this.int/100;
				this.sumPrice = this.goodsPrice-this.deduction+this.freight;
			}
		},
		onShow() {
			//页面显示时，加载订单信息
			uni.getStorage({
				key:'buylist',
				success: (ret) => {
					this.buylist = ret.data;
					this.goodsPrice=0;
					//合计
					let len = this.buylist.length;
					for(let i=0;i<len;i++){
						this.goodsPrice = this.goodsPrice + (this.buylist[i].number*this.buylist[i].price);
					}
					// 使用新的价格计算方法
					this.calculatePrice();
				}
			});
			//页面显示时，加载订单信息（如果不是秒杀商品）
			if (this.buylist.length === 0) {
				uni.getStorage({
					key:'buylist',
					success: (ret) => {
						this.buylist = ret.data;
						this.goodsPrice=0;
						//合计
						let len = this.buylist.length;
						for(let i=0;i<len;i++){
							this.goodsPrice = this.goodsPrice + (this.buylist[i].number*this.buylist[i].price);
						}
						this.deduction = this.int/100;
						this.sumPrice = this.goodsPrice-this.deduction+this.freight;
					}
				});
			}
			
			// 检查是否有用户选择的地址
			uni.getStorage({
				key:'selectAddress',
				success: (e) => {
					this.recinfo = e.data;
					uni.removeStorage({
						key:'selectAddress'
					})
				},
				fail: () => {
					// 只有在没有用户选择地址时，才请求默认地址
					// 并且确保不是从地址选择页面返回的情况
					if (!this.hasLoadedAddress) {
						this.loadDefaultAddress();
						this.hasLoadedAddress = true;
					}
				}
			})
			
			// 加载优惠券列表
			this.loadCouponList();
		},
		onHide() {
			
		},
		onBackPress() {
			//页面后退时候，清除订单信息
			this.clearOrder();
		},
		filters: {
			toFixed:function(x) {
				return parseFloat(x).toFixed(2);
			}
		},
		methods: {
			clearOrder(){
				uni.removeStorage({
					key: 'buylist',
					success: (res)=>{
						this.buylist = [];
						console.log('remove buylist success');
					}
				});
			},
			toPay(){
				// 验证订单信息
				if(this.buylist.length == 0){
					uni.showToast({title:'订单信息有误，请重新购买',icon:'none'});
					return;
				}
				
				// 验证收货地址
				if(!this.recinfo || !this.recinfo.id){
					uni.showToast({title:'请选择收货地址',icon:'none'});
					return;
				}
				
				// 显示加载提示
				uni.showLoading({
					title:'正在提交订单...'
				});
				
				// 构建订单参数数组（支持多个商品）
				const orderParams = this.buylist.map(item => {
					return {
						gid: item.id, // 商品ID
						aid: this.recinfo.id, // 地址ID
						cid: this.selectedCoupon ? this.selectedCoupon.id : null, // 优惠券ID（可选）
						freight: this.freight, // 运费
						number: item.number, // 订单数量
						spec: item.spec // 订单规格
					};
				});
				
				// 如果只有一个商品，直接提交单个订单
				// 如果有多个商品，需要根据后端API设计决定是批量提交还是逐个提交
				const submitParam = orderParams[0]; // 假设后端API一次只处理一个商品
				
				// 调用后端API提交订单
				api.submitOrder(submitParam).then(res => {
					uni.hideLoading();
					
					if(res && res.code === 200){
						// 订单提交成功，获取订单信息
						const orderData = res.data; // 后端返回的对象 {oid: 35, totalPrice: 1611.0}
						const totalPrice = orderData.totalPrice; // 获取总价
						const orderId = orderData.oid; // 获取订单ID
						
						// 清除本地购物车数据
						this.clearOrder();
						
						// 跳转到支付页面，可以传递订单ID和金额
						uni.redirectTo({
							url: `../pay/payment/payment?amount=${totalPrice}&orderId=${orderId}`
						});
					} else {
						uni.showToast({
							title: res.msg || '订单提交失败，请重试',
							icon: 'none'
						});
					}
				}).catch(err => {
					uni.hideLoading();
					console.error('提交订单失败:', err);
					uni.showToast({
						title: '网络错误，请重试',
						icon: 'none'
					});
				});
			},
			//选择收货地址
			selectAddress(){
				uni.navigateTo({
					url:'../user/address/address?type=select'
				})
			},
			
			// 新增优惠券选择方法
			selectCoupon() {
				// 过滤可用的优惠券（满足最低消费金额）
				const usableCoupons = this.availableCoupons.filter(coupon => {
					return this.goodsPrice >= coupon.minAmount;
				});
				
				if (usableCoupons.length === 0) {
					uni.showToast({
						title: '暂无可用优惠券',
						icon: 'none'
					});
					return;
				}
				
				// 显示优惠券选择弹窗，在名称前加前缀
				const itemList = usableCoupons.map(coupon => {
					const prefix = coupon.timeoutFlag === 1 ? '⏰ ' : '';
					return `${prefix}${coupon.name} (满${coupon.minAmount}减${coupon.discount})`;
				});
				
				uni.showActionSheet({
					itemList: ['不使用优惠券', ...itemList],
					success: (res) => {
						if (res.tapIndex === 0) {
							// 不使用优惠券
							this.selectedCoupon = null;
						} else {
							// 选择优惠券
							this.selectedCoupon = usableCoupons[res.tapIndex - 1];
						}
						// 重新计算价格
						this.calculatePrice();
					}
				});
			},
			
			// 新增价格计算方法
			calculatePrice() {
				// 计算积分抵扣
				this.deduction = this.int / 100;
				
				// 计算优惠券抵扣
				const couponDiscount = this.selectedCoupon ? this.selectedCoupon.discount : 0;
				
				// 计算最终价格
				this.sumPrice = this.goodsPrice - this.deduction - couponDiscount + this.freight;
				
				// 确保价格不为负数
				if (this.sumPrice < 0) {
					this.sumPrice = 0;
				}
			},
			
			// 新增加载优惠券列表方法
			loadCouponList() {
				api.getCouponList().then(res => {
					console.log('优惠券API响应:', res);
					
					if (res && res.code === 200 && res.data) {
						// 获取所有优惠券，不再过滤timeoutFlag
						this.availableCoupons = res.data.map(coupon => {
							// 转换API数据格式为页面所需格式
							return {
								id: coupon.id,
								name: coupon.name,
								discount: coupon.discount,
								minAmount: coupon.minAmount,
								expireDate: coupon.expireDate,
								timeoutFlag: coupon.timeoutFlag // 保存timeoutFlag信息
							};
						});
						
						console.log('可用优惠券列表:', this.availableCoupons);
					} else {
						console.error('获取优惠券列表失败:', res);
						uni.showToast({
							title: '获取优惠券失败',
							icon: 'none'
						});
					}
				}).catch(err => {
					console.error('调用优惠券API失败:', err);
					uni.showToast({
						title: '网络错误，请重试',
						icon: 'none'
					});
				});
			},
			
			// 新增获取默认地址方法
			loadDefaultAddress() {
				api.getDefaultAddress().then(res => {
					console.log('默认地址API响应:', res);
					
					if (res && res.code === 200 && res.data) {
						// 将API返回的数据格式转换为页面所需格式
						this.recinfo = {
							id: res.data.id,
							name: res.data.name,
							tel: res.data.phone,
							address: {
								region: {
									label: `${res.data.province}-${res.data.city}-${res.data.county}`,
									value: [0, 0, 0] // 这里可以根据需要设置具体的区域代码
								},
								detailed: res.data.detail
							},
							isDefault: res.data.defaultFlag === '1'
						};
						
						console.log('默认地址已加载:', this.recinfo);
					} else {
						console.error('获取默认地址失败:', res);
						uni.showToast({
							title: '获取默认地址失败',
							icon: 'none'
						});
					}
				}).catch(err => {
					console.error('调用默认地址API失败:', err);
					uni.showToast({
						title: '网络错误，请重试',
						icon: 'none'
					});
				});
			},
		}
	}
</script>

<style lang="scss">
.addr{
	width: 86%;
	padding: 20upx 3%;
	margin: 30upx auto 20upx auto;
	box-shadow: 0upx 5upx 20upx rgba(0,0,0,0.1);
	border-radius: 20upx;
	display: flex;
	.icon{
		width: 80upx;
		height: 80upx;
		display: flex;
		align-items: center;
		image{
			width: 60upx;
			height: 60upx;
		}
	}
	.tel-name{
		width: 100%;
		display: flex;
		font-size: 32upx;
		.tel{
			margin-left: 40upx;
		}
	}
	.addres{
		width: 100%;
		font-size: 26upx;
		color: #999;
	}
}
.buy-list{
	width: 86%;
	padding: 10upx 3%;
	margin: 30upx auto 20upx auto;
	box-shadow: 0upx 5upx 20upx rgba(0,0,0,0.1);
	border-radius: 20upx;
	.row{
		margin: 30upx 0;
		.goods-info{
			width: 100%;
			display: flex;
			.img{
				width: 22vw;
				height: 22vw;
				border-radius: 10upx;
				overflow: hidden;
				flex-shrink: 0;
				margin-right: 10upx;
				image{
					width: 22vw;
					height: 22vw;
				}
			}
			.info{
				width: 100%;
				height: 22vw;
				overflow: hidden;
				display: flex;
				flex-wrap: wrap;
				position: relative;
				.title{
					width: 100%;
					font-size: 28upx;
					display: -webkit-box;
					-webkit-box-orient: vertical;
					-webkit-line-clamp: 2;
					// text-align: justify;
					overflow: hidden;
				}
				.spec{
					font-size: 22upx;
					background-color: #f3f3f3;
					color: #a7a7a7;
					height: 40upx;
					display: flex;
					align-items: center;
					padding: 0 10upx;
					border-radius: 20upx;
					margin-bottom: 20vw;
				}
				.price-number{
					position: absolute;
					width: 100%;
					bottom: 0upx;
					display: flex;
					justify-content: space-between;
					align-items: flex-end;
					font-size: 28upx;
					height: 40upx;
					.price{
						color: #f06c7a;
					}
					.number{
						display: flex;
						justify-content: center;
						align-items: center;
						
					}
				}
			}
		}
	}
}
.order{
	width: 86%;
	padding: 10upx 3%;
	margin: 30upx auto 20upx auto;
	box-shadow: 0upx 5upx 20upx rgba(0,0,0,0.1);
	border-radius: 20upx;
	.row{
		margin: 20upx 0;
		height: 40upx;
		display: flex;
		align-items: center; // 添加垂直居中对齐
		.left{
			width: 120upx; // 设置固定宽度
			flex-shrink: 0; // 防止压缩
			font-size: 28upx;
		}
		.right{
			flex: 1; // 占据剩余空间
			margin-left: 20upx; // 减少左边距
			font-size: 26upx;
			color: #999;
			input{
				font-size: 26upx;
				color: #999;
			}
		}
	}
}
.coupon-select {
	display: flex;
	justify-content: space-between;
	align-items: center;
	width: 100%;
	.placeholder {
		color: #ccc;
	}
	.arrow {
		color: #999;
		font-size: 24upx;
	}
}
.blck{
	width: 100%;
	height: 100upx;
}
.footer{
		width: 92%;
		padding: 0 4%;
		background-color: #fbfbfb;
		height: 100upx;
		display: flex;
		justify-content: flex-end;
		align-items: center;
		font-size: 28upx;
		position: fixed;
		bottom: 0upx;
		z-index: 5;
		
		.settlement{
			width: 80%;
			display: flex;
			justify-content: flex-end;
			align-items: center;
			.sum{
				width: 50%;
				font-size: 28upx;
				margin-right: 10upx;
				display: flex;
				justify-content: flex-end;
				.money{
					font-weight: 600;
				}
			}
			.btn{
				padding: 0 30upx;
				height: 60upx;
				background-color: #f06c7a;
				color: #fff;
				display: flex;
				justify-content: center;
				align-items: center;
				font-size: 30upx;
				border-radius: 40upx;
			}
		}
	}
.detail{
	width: 86%;
	padding: 10upx 3%;
	margin: 30upx auto 20upx auto;
	box-shadow: 0upx 5upx 20upx rgba(0,0,0,0.1);
	border-radius: 20upx;
	.row{
		height: 60upx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		.nominal{
			font-size: 28upx;
		}
		.content{
			font-size: 26upx;
			color: #f06c7a;
		}
	}
}
</style>
